package com.jcfk.eam.service.base;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamAssetTypeDao;
import com.jcfk.eam.domain.dto.base.EamAssetTypeDTO;
import com.jcfk.eam.domain.po.base.EamAssetType;
import com.jcfk.eam.domain.query.base.EamAssetTypeQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 资产类型
 *
 * @author libinghai
 * @date 2024-07-23
 */
@Service
public class EamAssetTypeService extends BaseService<EamAssetTypeDao, EamAssetType> {

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<MdmEquipTypeDTO>
     */
    public List<EamAssetTypeDTO> getList(EamAssetTypeQuery query) {
        // 查询条件
        QueryWrapper<EamAssetType> qw = new QueryWrapper<>();
        qw.lambda().eq(query.getAssetKind() != null, EamAssetType::getAssetKind, query.getAssetKind());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetTypeCode()), EamAssetType::getAssetTypeCode, query.getAssetTypeCode());
        qw.lambda().eq(!StrUtil.isEmpty(query.getParentTypeId()), EamAssetType::getParentTypeId, query.getParentTypeId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetTypeName()), EamAssetType::getAssetTypeName, query.getAssetTypeName());
        qw.lambda().eq(query.getEnabled() != null, EamAssetType::getEnabled, query.getEnabled());
        qw.lambda().eq(EamAssetType::getDeleted, DeleteFlag.NOTDELETED.getValue());
        // 查询数据
        List<EamAssetType> list = super.list(qw);

        return convertList(list, EamAssetTypeDTO.class);
    }

    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EamAssetTypeDTO> getTree(EamAssetTypeQuery query) {
        List<EamAssetTypeDTO> tree = new ArrayList<>();
        // 获取所有类型
        List<EamAssetTypeDTO> allList = this.getList(query);
        // 排序
        allList.sort(Comparator.comparing(EamAssetTypeDTO::getSort));

        Map<String, List<EamAssetTypeDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EamAssetTypeDTO node : allList) {
            String parentTypeId = node.getParentTypeId();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EamAssetTypeDTO> getAvailableList(EamAssetTypeQuery query) {
        List<EamAssetTypeDTO> tree = new ArrayList<>();
        // 获取所有类型
        query.setParentTypeId("0");
        List<EamAssetTypeDTO> allList = this.getList(query);
        // 排序
        allList.sort(Comparator.comparing(EamAssetTypeDTO::getSort));

        Map<String, List<EamAssetTypeDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EamAssetTypeDTO node : allList) {
            String parentTypeId = node.getParentTypeId();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private static void buildTree(List<EamAssetTypeDTO> tree, Map<String, List<EamAssetTypeDTO>> parentChildMap, String parentTypeId) {
        List<EamAssetTypeDTO> children = parentChildMap.get(parentTypeId);
        if (children != null) {
            for (EamAssetTypeDTO child : children) {
                List<EamAssetTypeDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 判断MdmEquipType是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamAssetTypeDTO dto) {
        QueryWrapper<EamAssetType> qw = new QueryWrapper<>();
        Integer count = 0;
        // 判断编号
        if (StrUtil.isNotEmpty(dto.getAssetTypeCode())) {
            // 修改时添加条件
            if (!StrUtil.isEmpty(dto.getId())) {
                qw.lambda().ne(EamAssetType::getId, dto.getId());
            }
            qw.lambda().eq(EamAssetType::getAssetKind, dto.getAssetKind());
            qw.lambda().eq(EamAssetType::getAssetTypeCode, dto.getAssetTypeCode());
            qw.lambda().eq(EamAssetType::getDeleted, DeleteFlag.NOTDELETED.getValue());

            count = this.baseMapper.selectCount(qw);
            if (count > 0) {
                return RetResult.fail("编号已存在");
            }
        }
        return RetResult.ok();
    }

    /**
     * 插入资产类型
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamAssetTypeDTO dto) {

        // 保存
        EamAssetType item = new EamAssetType();
        BeanUtils.copyProperties(dto, item);
        item.setId(IdUtils.simpleUUID());
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.save(item);
    }

    /**
     * 更新设备类型
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamAssetTypeDTO dto) {

        // 保存
        EamAssetType item = new EamAssetType();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.updateById(item);
    }

    /**
     * 根据批量主键删除设备类型(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamAssetTypeDTO dto) {

        EamAssetType item = new EamAssetType();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamAssetType> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamAssetType item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreatedUserName(SecurityUtils.getUserName());
            item.setVersion(1L);
            item.setDeleted(DeleteFlag.NOTDELETED.getValue());
            item.setCreateTime(new Date());
        }

        if (item.getSort() == null) {
            item.setSort(1);
        }

        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setLastUpdateTime(new Date());


    }

    /**
     * 根据主键获取资产类型信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamAssetTypeDTO get(String id) {
        // 查询数据
        EamAssetType item = this.baseMapper.selectById(id);
        EamAssetTypeDTO dto = new EamAssetTypeDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    public void setAllInfo(EamAssetType item) {
        QueryWrapper<EamAssetType> qw = new QueryWrapper<>();
        qw.lambda().eq(EamAssetType::getId, item.getParentTypeId());

        EamAssetType parentType = this.baseMapper.selectOne(qw);
        if (parentType == null) {
            item.setAllId(item.getId());
            item.setAllCode(item.getAssetTypeCode());
            item.setAllName(item.getAssetTypeName());
        } else {
            item.setAllId(parentType.getAllId() + "," + item.getId());
            item.setAllCode(parentType.getAllCode() + "," + item.getAssetTypeCode());
            item.setAllName(parentType.getAllName() + "," + item.getAssetTypeName());
        }
    }

    /**
     * 判断是否有下级
     *
     * @param id
     * @return
     */
    public Boolean isHaveChild(String id) {
        QueryWrapper<EamAssetType> qw = new QueryWrapper<>();
        qw.lambda().eq(EamAssetType::getParentTypeId, id).eq(EamAssetType::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(qw);
        return count > 0 ? true : false;
    }
}

